package cn.itrip.commons;

import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 处理日期类型变量的工具类
 *
 * @author donghai
 * @version v1.0
 * @since 2017/04/20
 */
public class DateUtil {
	/**
	 * 获取两个日期之间的日期
	 *
	 * @param start 开始日期
	 * @param end   结束日期
	 * @return 日期字符串格式的集合
	 */
	public static List<Date> getBetweenDates(Date start, Date end) {
		List<Date> result = new ArrayList<Date>();
		Calendar tempStart = Calendar.getInstance();
		tempStart.setTime(start);

		Calendar tempEnd = Calendar.getInstance();
		tempEnd.setTime(end);
		while (tempStart.before(tempEnd) || tempStart.equals(tempEnd)) {
			result.add(tempStart.getTime());
			tempStart.add(Calendar.DAY_OF_YEAR, 1);
		}
		return result;
	}

	/**
	 * 根据日期字符串返回日期
	 *
	 * @param source
	 * @param format
	 * @return
	 * @throws ParseException
	 */
	public static final Date parse(String source, String format) throws ParseException {
		DateFormat df = new SimpleDateFormat(format);
		return df.parse(source);
	}

	/**
	 * 根据日期获取格式化的日期字符串
	 *
	 * @param date
	 * @param format
	 * @return
	 * @throws ParseException
	 */
	public static final String format(Date date, String format) throws ParseException {
		DateFormat df = new SimpleDateFormat(format);
		return df.format(date);
	}

	//去掉时间戳后面的Z
	public static final Date parseJsDateWidthZone(String date) {
		final String Z_VAL = "Z";
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
		if (StringUtils.hasText(date) && date.endsWith(Z_VAL)) {
			String z = date.substring(0, date.length() - 1);
			try {
				return simpleDateFormat.parse(z);
			} catch (ParseException e) {
				return null;
			}
		}
		return null;
	}

	public static int DaysCount(Date from,Date to) throws ParseException {
		Calendar calendar1 = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();
		calendar1.setTime(from);
		calendar2.setTime(to);
		int Days = 0;
		for(;calendar1.before(calendar2);
			calendar1.add(Calendar.DATE,1)){
			Days++;
		}
		return Days;
	}

    /*public static void main(String[] args) throws ParseException {
        *//*System.out.println("this.parseJsDateWidthZone(\"2022-04-16T00:00:00.000Z\") = " +
                parseJsDateWidthZone("2022-04-16T00:00:00.000Z"));*//*
		SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
		System.out.println("DaysCount(new Date(\"2022-04-01\"),new Date(\"2022-04-20\")) = "
				+ DaysCount(s.parse("2022-04-01"), s.parse("2022-04-5")));
	}*/
}
